package com.example.module_home.View;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.FragmentUtils;
import com.example.module_base.Base.BaseActivity;
import com.example.module_base.Controll.MyToolBar;
import com.example.module_home.Adapter.SearchContentAdapter;
import com.example.module_home.Base.BaseStackFragment;
import com.example.module_home.Entity.CodeInfo;
import com.example.module_home.Entity.CodeTree;
import com.example.module_home.Entity.SearchInfo;
import com.example.module_home.Entity.UserOperationInfo;
import com.example.module_home.Module.CodeBank.CodeBankManager;
import com.example.module_home.Public.Constant;
import com.example.module_home.R;
import com.example.module_home.Utils.DialogUtil;
import com.example.module_home.View.Fragment.HMCodeWebFragment;
import com.example.module_home.View.Fragment.HMOperationFragment;
import com.example.module_home.View.Fragment.HMPersonalFragment;
import com.example.module_home.View.Fragment.HMUpdateFragment;
import com.example.module_home.View.View.ExpandableLinearLayout;
import com.example.module_home.View.View.TreeView;
import com.example.module_home.databinding.HomeActivityMainBinding;
import com.unnamed.b.atv.view.AndroidTreeView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;

@Route(path="/home/main")
public class HomeMainActivity extends BaseActivity<HomeActivityMainBinding>{
    private static final String TAG = "HomeMainActivity";
    private String mUserPassword;
    private String mUserName;
    private boolean isRemember;
    private String[] mTitles = {"最近操作","我的"};
    private SharedPreferences.Editor mEditor;
    private Toolbar mToolBar;
    private boolean isHome = true;
    private List<String> mTypeSelectList;
    private SearchContentAdapter mSearchContentAdapter;
    private HMPersonalFragment mPersonalFragment;

    @Override
    public int setLayout() {
        return R.layout.home_activity_main;
    }

    @Override
    public void init(HomeActivityMainBinding bingding) {
        setupToolbar();
        getLoginActivityInfo();
        getSeenCodeInfo();
        setupTreeView();
        setupContentMain();
        setupWebView();
    }

    private void getSeenCodeInfo() {

    }

    private void setupWebView() {
        WebSettings settings = bingding.layoutMain.webCode.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setSupportZoom(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
    }

    private void setupTreeView() {
        TreeView treeView = new TreeView(this,bingding.contentMenu.treeContainer);
        treeView.init();
        treeView.setTreeViewParamsListener(new TreeView.TreeViewParamsListener() {
            @Override
            public void showCodeInfo(int kindId) {
                seeingCodeInfo(kindId);
            }

            @Override
            public void showCodeTreeInfo(List<CodeTree> codeTrees) {
                mTypeSelectList = new ArrayList<>();
                mTypeSelectList.add(0,"所有");
                for(CodeTree codeTree:codeTrees){
                    //添加树状图最顶层的类型
                    mTypeSelectList.add(codeTree.getText());
                }
                bingding.contentMenu.spTypeSelect.attachDataSource(mTypeSelectList);
            }
        });
    }

    /**
     * 查看文章
     * @param kindId 文章信息
     */
    public void seeingCodeInfo(int kindId) {
//        mPersonalFragment.addSeenCode(info);
//        mToolBar.setTitle(info.getTitle());
//        mToolBar.setNavigationIcon(R.drawable.ic_home_black_24dp);
        Intent intent = new Intent(this, HomeCodeActivity.class);
        intent.putExtra(Constant.CODE_ID,kindId);
        startActivity(intent);
//        isHome = false;
//        bingding.layoutMain.linePager.setVisibility(View.GONE);
//        bingding.layoutMain.webCode.setVisibility(View.VISIBLE);
//        bingding.layoutMain.setCodeInfo(info);
        bingding.drawerLayout.closeDrawer(Gravity.START);
    }

    private void setupContentMain() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(new HMOperationFragment());
        mPersonalFragment = new HMPersonalFragment();
        fragments.add(mPersonalFragment);
        bingding.layoutMain.tabLayout.setViewPager(bingding.layoutMain.vp,mTitles,this,fragments);
    }


    /**
     * 获取登陆页面的用户信息及操作信息
     */
    private void getLoginActivityInfo() {
        mUserName = getIntent().getStringExtra(Constant.USER_NAME);
        mUserPassword = getIntent().getStringExtra(Constant.USER_PASSWORD);
        isRemember = getIntent().getBooleanExtra(Constant.IS_REMEMBER,false);
        mEditor = getSharedPreferences(Constant.SAVE_USER_INFO, Context.MODE_PRIVATE).edit();

        if(isRemember){
            //如果记住密码，那么存储用户账号和密码，和记住密码状态为true
            mEditor.putString(Constant.USER_NAME,mUserName);
            mEditor.putString(Constant.USER_PASSWORD,mUserPassword);
            mEditor.putBoolean(Constant.IS_REMEMBER,true);
        }else {
            //否则，记住密码状态为false
            mEditor.putBoolean(Constant.IS_REMEMBER,false);
        }
        mEditor.apply();
    }

    private void setupToolbar() {
        mToolBar = new MyToolBar(this)
                .init()
                .addTitle("IT资源库")
                .addHome(R.drawable.ic_code_bank, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(isHome){
                            bingding.drawerLayout.openDrawer(Gravity.START);
                        }else {
                            bingding.layoutMain.webCode.setVisibility(View.GONE);
                            bingding.layoutMain.linePager.setVisibility(View.VISIBLE);
                            mToolBar.setNavigationIcon(R.drawable.ic_code_bank);
                            mToolBar.setTitle("IT资源库");
                            isHome = true;
                        }
                    }
                });
        addToolBar(bingding.layoutMain.lineToolbar, mToolBar);
    }


    private void addFragment(Fragment fragment,String tag) {
        getSupportFragmentManager().beginTransaction()
                .addToBackStack(null)
                .add(R.id.container,fragment,tag)
                .commit();
    }

    @Override
    public void onBackPressed() {
        BaseStackFragment topInStack = (BaseStackFragment) FragmentUtils.getTopInStack(getSupportFragmentManager());
        if(topInStack!=null){
            topInStack.onBackClick();
        }
        if(!isHome){
            isHome = true;
            mToolBar.setNavigationIcon(R.drawable.ic_code_bank);
            mToolBar.setTitle("IT资源库");
            bingding.layoutMain.webCode.setVisibility(View.GONE);
            bingding.layoutMain.linePager.setVisibility(View.VISIBLE);
        }else {
            DialogUtil.showBackDialog(this);
        }
    }

    /**
     * 左边菜单中的一些点击事件
     * @param view
     */
    public void onLeftMenuClick(View view) {
        int id = view.getId();
        if(id==R.id.default_toggle){
            bingding.contentMenu.conSearch.setVisibility(View.VISIBLE);
            Animation popupAnim = AnimationUtils.loadAnimation(this, R.anim.popup_flyout_show);
            bingding.contentMenu.conSearch.startAnimation(popupAnim);
            bingding.contentMenu.conDefault.setVisibility(View.GONE);
            bingding.contentMenu.treeContainer.setVisibility(View.GONE);
            bingding.contentMenu.layoutSearch.setVisibility(View.VISIBLE);
        }else if(id==R.id.search_toggle) {
            bingding.contentMenu.conDefault.setVisibility(View.VISIBLE);
            bingding.contentMenu.conSearch.setVisibility(View.GONE);
            bingding.contentMenu.treeContainer.setVisibility(View.VISIBLE);
            bingding.contentMenu.layoutSearch.setVisibility(View.GONE);
        }else if(id==R.id.btn_search){
            final String title = bingding.contentMenu.etSearch.getText().toString();
            int selectedIndex = bingding.contentMenu.spTypeSelect.getSelectedIndex();
            String typeSelect = mTypeSelectList.get(selectedIndex);
            CodeBankManager.getInstance(this).getSearchInfo(title, typeSelect, DialogUtil.showLoadingDialog(this), new CodeBankManager.CodeBankBack<List<SearchInfo>>() {
                @Override
                public void successful(final List<SearchInfo> searchInfo) {
                    List<String> titles = new ArrayList<>();
                    List<List<Integer>> indexes = new ArrayList<>();
                    for(SearchInfo info:searchInfo){
                        titles.add(info.getTitleapp());
                        indexes.add(info.getIndex());
                    }
                    mSearchContentAdapter = new SearchContentAdapter(HomeMainActivity.this,titles,indexes);
                    bingding.contentMenu.listSearch.setAdapter(mSearchContentAdapter);
                    bingding.contentMenu.listSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            CodeBankManager.getInstance(HomeMainActivity.this)
                                    .getCodeInfo(searchInfo.get(position).getKindid(),
                                            DialogUtil.showLoadingDialog(HomeMainActivity.this),
                                            new CodeInfoListener());
                        }
                    });
                }

                @Override
                public void failed(int code, String e) {

                }
            });
        }
    }

    public class CodeInfoListener implements CodeBankManager.CodeBankBack<CodeInfo>{

        @Override
        public void successful(CodeInfo codeInfo) {
            HomeMainActivity.this.seeingCodeInfo(codeInfo.getKindID());
        }

        @Override
        public void failed(int code, String e) {

        }
    }
}
